#!/usr/bin/env python
"""
调试构建脚本
用于调试 setup.py 的构建过程
"""

import os
import sys
import subprocess
import shutil

def clean_build():
    """清理构建目录"""
    print("=== 清理构建目录 ===")
    dirs_to_clean = ['build', 'dist', '*.egg-info']
    for pattern in dirs_to_clean:
        if os.path.exists(pattern):
            if os.path.isdir(pattern):
                shutil.rmtree(pattern)
                print(f"已删除目录: {pattern}")
            else:
                os.remove(pattern)
                print(f"已删除文件: {pattern}")

def debug_build():
    """调试构建过程"""
    print("=== 开始调试构建 ===")
    
    # 设置环境变量
    env = os.environ.copy()
    env['DISTUTILS_DEBUG'] = '1'
    env['SETUPTOOLS_USE_DISTUTILS'] = 'stdlib'
    
    # 运行构建命令
    cmd = [sys.executable, 'setup.py', 'build_ext', '--inplace', '--force', '--verbose']
    print(f"执行命令: {' '.join(cmd)}")
    
    try:
        result = subprocess.run(cmd, env=env, capture_output=False, text=True)
        print(f"构建完成，返回码: {result.returncode}")
        return result.returncode == 0
    except Exception as e:
        print(f"构建失败: {e}")
        return False

def list_build_outputs():
    """列出构建产物"""
    print("=== 构建产物 ===")
    for root, dirs, files in os.walk('.'):
        for file in files:
            if file.endswith(('.pyd', '.so', '.dll')):
                filepath = os.path.join(root, file)
                size = os.path.getsize(filepath)
                print(f"找到: {filepath} (大小: {size} 字节)")

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='调试构建脚本')
    parser.add_argument('--clean', action='store_true', help='清理构建目录')
    parser.add_argument('--build', action='store_true', help='执行构建')
    parser.add_argument('--list', action='store_true', help='列出构建产物')
    
    args = parser.parse_args()
    
    if args.clean:
        clean_build()
    
    if args.build:
        success = debug_build()
        if not success:
            sys.exit(1)
    
    if args.list:
        list_build_outputs()
    
    # 如果没有参数，执行全部
    if not any([args.clean, args.build, args.list]):
        clean_build()
        success = debug_build()
        if success:
            list_build_outputs()
        else:
            sys.exit(1) 